﻿using DevExpress.Web.ASPxGridView;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ERB.App_Code.BAL.CRM;
using System.Data;
using Microsoft.ApplicationBlocks.Data;
using ERB.App_Code;

namespace ERB.Modules.CRM
{
    public partial class Customer : BasePage
    {
        #region Properties
        CustomerClass cus = new CustomerClass();

        #endregion

        #region method
        public void Exec_Customer(string action)
        {
            cus.BankID = txtBank.Text == "" ? -1 : Convert.ToInt32(txtBank.Text);
            cus.RegencyID = -1;
            cus.CustomerGroupID = -1;
            cus.TermID = -1;
            cus.StatusID = -1;
            cus.CustomerCode = "Cus00001";
            cus.CustomerName = txtCustomerName.Text.Trim() == "" ? "" : txtCustomerName.Text.Trim();
            cus.CustomerContact = txtContact.Text.Trim() == "" ? "" : txtContact.Text.Trim();
            cus.Address = txtAddress.Text == "" ? "" : txtAddress.Text;
            cus.Phone = txtPhone.Text.ToString() == "" ? "" : txtPhone.Text.ToString();
            cus.ImageURL = "";
            cus.Website = txtWebsite.Text.Trim() == "" ? "" : txtWebsite.Text.Trim();
            cus.Email = txtEmail.Text.Trim() == "" ? "" : txtEmail.Text.Trim();
            cus.Mobile = txtMobile.Text.ToString() == "" ? "" : txtMobile.Text.ToString();
            cus.Fax = txtFax.Text.ToString() == "" ? "" : txtFax.Text.ToString();
            cus.TaxCode = txtTaxCode.Text.ToString() == "" ? "" : txtTaxCode.Text.ToString();
            cus.BankAccount = txtBankAcount.Text.ToString() == "" ? "" : txtBankAcount.Text.ToString();
            cus.BOID = "1";
            cus.UserCreate = "1";

            if (action == "Insert")
            {
                bool result = CustomerClass.Insert(cus);
            }
            else if (action == "Update")
            {
                string str_code = hfID.Value;
                cus.CustomerID = Convert.ToInt32(str_code);
                CustomerClass.Update(cus);
            }
        }

        protected void ReloadControl()
        {
            txtCustomerName.Text = "";
            CboTerm.Value = "";
            txtBank.Text = "";
            txtBankAcount.Value = "";
            txtAddress.Text = null;
            txtPhone.Value = "";
            txtContact.Text = "";
            txtMobile.Value = "";
            txtEmail.Text = "";
            txtFax.Value = "";
            txtWebsite.Text = "";
            txtDateCreate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            txtTaxCode.Value = "";
            chkonhold.Checked = false;
        }

        protected void ImportExcel(string Excel)
        {
            //DataTable dt = ArCustomer.exceldata(string.Concat(Server.MapPath("~/uploads/excel/" + Excel)));
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    cus.CustomerName = dt.Rows[i]["Customer Name"].ToString();
            //    cus.Bank = dt.Rows[i]["Bank"].ToString();
            //    cus.BankAccount = dt.Rows[i]["Bank Account"].ToString();
            //    string Days = dt.Rows[i]["Payment Method (days)"].ToString();
            //    DataTable Term = TblTerms.Get_TblTerms_SearchDueDays(Convert.ToDecimal(Days));
            //    cus.TermsCode = Term.Rows[0]["TermsCode"].ToString();
            //    cus.SoldToAddr1 = dt.Rows[i]["Address"].ToString();
            //    cus.SoldToAddr2 = "";
            //    cus.SoldToAddr3 = "";
            //    cus.SoldDistrict = "";
            //    cus.SoldCity = "";
            //    cus.ShipToAddr1 = dt.Rows[i]["Address"].ToString();
            //    cus.ShipToAddr2 = "";
            //    cus.ShipToAddr3 = "";
            //    cus.ShipDistrict = "";
            //    cus.ShipCity = "";
            //    cus.Phone = dt.Rows[i]["Phone"].ToString();
            //    cus.Handphone = dt.Rows[i]["Mobile"].ToString();
            //    cus.Email = dt.Rows[i]["Email"].ToString();
            //    cus.Fax = dt.Rows[i]["Fax"].ToString();
            //    cus.Contact = dt.Rows[i]["Contact Name"].ToString();
            //    cus.Website = dt.Rows[i]["Website"].ToString();
            //    cus.DateCustAdded = DateTime.Now.ToString("MM/dd/yyyy");
            //    cus.CompanyTaxNumber = dt.Rows[i]["TaxCode"].ToString();
            //    cus.CreditStatus = "N";
            //    cus.CreditCheckFlag = "N";
            //    cus.OnHold = dt.Rows[i]["Discontinue"].ToString();

            //    cus.Customer = (Convert.ToInt32(ArCustomer.IdMaxtOfArCustomer()) + 1).ToString();
            //    ArCustomer.InsertArCustomer(cus);
            //    SqlHelper.ExecuteScalar(DataServices.ConnectString, "TblSysSetting_update", "Customer", cus.Customer);
            //}
        }
        #endregion

        #region event handler
        protected void cpLoadData_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            if (e.Parameter.StartsWith("LoadDataEdit"))
            {
                cus.CustomerID = Convert.ToInt32(e.Parameter.Split(';')[1]);
                cus.BOID = "1";
                DataTable dt = CustomerClass.SelectByID(cus);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    txtCustomerName.Text = dt.Rows[i]["CustomerName"].ToString();
                    CboTerm.Value = dt.Rows[i]["TermID"].ToString();
                    txtBank.Text = dt.Rows[i]["BankID"].ToString();
                    txtBankAcount.Value = dt.Rows[i]["BankAccount"].ToString();
                    txtAddress.Text = dt.Rows[i]["Address"].ToString();
                    txtPhone.Value = dt.Rows[i]["Phone"].ToString();
                    txtContact.Text = dt.Rows[i]["CustomerContact"].ToString();
                    txtMobile.Value = dt.Rows[i]["Mobile"].ToString();
                    txtEmail.Text = dt.Rows[i]["Email"].ToString();
                    txtFax.Value = dt.Rows[i]["Fax"].ToString();
                    txtWebsite.Text = dt.Rows[i]["Website"].ToString();
                    txtDateCreate.Text = Convert.ToDateTime(dt.Rows[i]["CreateDate"].ToString()).ToString("dd/MM/yyyy");
                    txtTaxCode.Text = dt.Rows[i]["TaxCode"].ToString();
                }
            }
            else
            {
                ReloadControl();
            }
        }
        protected void ASPxGridView1_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            if (e.Parameters.IndexOf("delselect") >= 0)
            {
                List<object> keyValues = ASPxGridView1.GetSelectedFieldValues("CustomerID");
                for (int i = 0; i < keyValues.Count; i++)
                {

                    cus.CustomerID = Convert.ToInt32(keyValues[i].ToString());
                    cus.BOID = "1";
                    bool checkDelete = CustomerClass.Delete(cus);

                    if (checkDelete)
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(),
                        "temp", "<script type='text/javascript'>alert(" + "meo meo" + ");</script>", false);
                    }

                }
                ASPxGridView1.Selection.UnselectAll();
                ASPxGridView1.DataBind();
            }
            else
            {
                ASPxGridView1.Selection.UnselectAll();
                ASPxGridView1.DataBind();
            }
        }
        protected void cpReloadGrid_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            if (e.Parameter.StartsWith("Insert"))
            {
                try
                {
                    Exec_Customer("Insert");
                    e.Result = "Success";
                }
                catch (Exception ex)
                {
                    e.Result = "Error";
                    Console.Write(ex);
                }
            }
            else if (e.Parameter.StartsWith("Update"))
            {
                try
                {
                    Exec_Customer("Update");
                    e.Result = "Success";
                }
                catch
                {
                    e.Result = "Error";
                }
            }
            else if (e.Parameter.StartsWith("SaveNew"))
            {
                try
                {
                    Exec_Customer("Insert");
                    e.Result = "SuccessAndNew";
                }
                catch (Exception ex)
                {
                    e.Result = "Error";
                    Console.Write(ex);
                }
            }
            else if (e.Parameter.StartsWith("Import"))
            {
                try
                {
                    ImportExcel(e.Parameter.Split(';')[1].ToString());
                    e.Result = "SuccessImport";
                }
                catch (Exception ex)
                {
                    e.Result = "Error";
                    Console.Write(ex);
                }
            }
        }

        protected void LoadGrid_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            ASPxGridView1.DataBind();
        }

        public void Check_Permission(string str_permission)
        {
            switch (str_permission)
            {
                case "F":
                    NavControl.delscript = "True";
                    break;
                case "R":
                    NavControl.addnewscript = "";
                    NavControl.delscript = "Invisible";
                    break;
                case "W":
                    NavControl.delscript = "Invisible";
                    break;
                default:
                    NavControl.delscript = "Invisible";
                    break;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //if (Session["user"] == null)
                //{
                //    Response.Redirect("../../Login.aspx");
                //}
                baseGv = ASPxGridView1;
                NavControl.gv = ASPxGridView1;
                ASPxGridView1.DataBind();
                //Session["permission"] = serPermission.GetPermissionOFAccount(Session["user"].ToString(), "Customer.aspx", "Master");
                //Check_Permission(Session["permission"].ToString().Trim());
            }
        }
        #endregion
    }
}